<template>
	<div class="login">
		<!-- 导航栏 -->
		<van-nav-bar :title="flag?'登录':'注册'"  left-arrow>
		  <template #right>
		    <van-icon name="ellipsis" size="18" />
		  </template>
		</van-nav-bar>
		
		<!-- 表单组件 -->
		<van-form @submit="onSubmit">
		  <van-field
		    v-model="username"
		    name="用户名"
		    label="用户名"
		    placeholder="用户名"
		    :rules="[{ required: true, message: '请填写用户名' }]"
		  />
		  <van-field
		    v-model="password"
		    type="password"
		    name="密码"
		    label="密码"
		    placeholder="密码"
		    :rules="[{ required: true, message: '请填写密码' }]"
		  />
		  
	      <Verify @success="alert('success')"
		   @error="alert('error')" 
		   :type="2"
		   :showButton="false"
		   fontSize="22px"
		   width="50%"
		   ref="verify"
		   ></Verify>
		   
		   <p class="toggle" @click="toggle">{{flag?"立即注册":"已有登录账号"}}</p>
		   
		  <div style="margin: 16px;">
		    <van-button round block type="info" native-type="submit">
				{{flag?"登录":"注册"}}
			</van-button>
		  </div>
		</van-form>
	</div>
</template>

<script>
	import Verify from 'vue2-verify'
	export default{
		name:"Login",
		data() {
		    return {
		      username: '',
		      password: '',
			  flag:true,//true 登录  false 注册
			  codeflag:false//验证码是否验证通过
		    };
		},
		methods: {
			alert(text) {
			    this.codeflag = text=="success"?true:false;
			},
			toggle(){
				this.flag=!this.flag
				//用户名和密码清空
				this.username=this.password="";
			},
		    onSubmit(values) {
			  console.log(this.$refs.verify);
			  this.$refs.verify.checkCode();
		      if(this.codeflag){//true--验证码通过
				if(this.flag){//登录
					 this.$http.login(this.username,this.password)
					 .then(res=>{
						 if(+res.resultCode===200){
						    //1.存储token
							localStorage.setItem("xfdata",res.data);
							
							if(this.$route?.query?.needback){
								this.$router.back();//返回上一级页面，商品详情页
							}else{
								//2.跳转到首页
								this.$router.push("/home");
							}
							
						 }
					 }).catch(err=>{
						 console.log(err);
					 }) 
				}else{//注册
					this.$http.register(this.username,this.password)
					.then(res=>{//注册成功，会重新进入登录页面，去登录
						if(+res.resultCode===200){
							this.flag=true;//进入登录页面
							this.$refs.verify.refresh();//刷新验证码
							this.username=this.password="";//账号密码为空
						}
					}).catch(err=>{
						console.log(err);
					})
				}
			  }
		    }
		},
		components: {
		    Verify
		}
	}
</script>

<style scoped lang="less">
	.van-form{
		margin-top:80px;
		.toggle{
			font-size:16px;
			line-height:40px;
			text-indent:1em;
			color:#1989FA;
		}
	}
	/deep/.cerify-code-panel{
		margin-top:20px;
		display:flex;
		width:100%;
		.verify-code-area{
			display:flex;
			line-height:65px;
			.verify-change-code{
				display: inline-block;
				font-size:18px;
				margin-top:20px;
			}
		}
	}
</style>
